import axios from 'axios'
import store from '../store'
import { error } from '../utils/toast'
import { getItem, removeItem } from '../utils/save'
import router from '../router'

// 创建实例时设置配置的默认值
// axios.defaults.withCredentials = true

const service = axios.create({
  baseUrl: location.origin,
  timeout: 1000 * 60 * 5,
  withCredentials: true // 允许添加cookie
})

// 添加响应拦截器
service.interceptors.response.use(res => {
    const { data } = res

    if (!data) {
      error("==response==", res.data.message)
    }
    return res.data
}, err => {
//  if (err.response.status == 403 || err.response.status == 401) {
    if (err.response.status == 401) {
    removeItem('user_info')
    removeItem("nav_active")
    // store.commit('setLoginDlg', {visual:true, type:true})
    location.reload()
    router.push({path:'/'})
  }

  return Promise.reject(err)
})

/**
* 统一发送请求
*  config 请求参数
*/
export function request(config) { 
    const user_id = getItem('user_info') ? getItem('user_info').user_id : 0
    /* 考虑ie浏览器强大缓存问题，接口链接添加时间戳_t */
    const nowTime = Date.parse(new Date()) / 1000
    // 本地mock情况下取testUrl字段 统一使用location.origin
    if (config['baseUrl']) {
      config['url'] = config['baseUrl'] + config['url']
    } 
  
  // config['headers'] = {'Content-Type': 'audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3'}
  // get请求时替换掉 字段data 为params
  if (config['url'].includes('?')) {
    config.url += (`&_t=${nowTime}`)
  } else {
    config.url += (`?_t=${nowTime}`)
  }

  if (config['method'].toLowerCase() === 'get') {
    config['params'] = { ...config['data'] }
    delete config['data']
  } 
  
  if (user_id > 0) { 
    config.url += (`&user_id=${user_id}`)
  }
  
  return service(config)
}